// stores/captchaStore.js
import { defineStore } from 'pinia';
import axiosInstance from '@/utils/axios';
import { usemsgStore } from './msgwrapper';

export const usecaptchaStore = defineStore('captchaStore', {
  state: () => ({
    timer: null,
    isButtonDisabled:false,
    countdown: 0,
  }),
  actions: {
    async getCaptcha(username) {
      const msgStore = usemsgStore();
      const { sendMessage } = msgStore;
      try {
        if (!username) {
          sendMessage("error", "请填写手机号");
          return;
        }
        // 初始化状态
        this.isButtonDisabled = true;
        this.countdown = 60;
    
        // 清除之前的计时器（如果有）
        if (this.timer) {
          clearInterval(this.timer);
        }
    
        // 设置倒计时逻辑
        this.timer = setInterval(() => {
          if (this.countdown > 0) {
            this.countdown -= 1;
          } else {
            clearInterval(this.timer);
            this.isButtonDisabled = false; // 倒计时结束后按钮可用
          }
        }, 1000);
    
        // 发送验证码请求
        const res = await axiosInstance.get('/api/getcode', { params: { username } });
        console.log(res)
        if (res.data.success && res.data.code === 200) {
          sendMessage("success", "短信已成功发送，请查看");
        } else {
          sendMessage("error", "请求失败，请稍后再试");
        }
      } catch (error) {
        sendMessage("error", "获取验证码失败，请稍后再试。");
      }
    },
      resetCountdown() {
        this.isButtonDisabled = false;
        this.countdown = 0;
        if (this.timer) {
          clearInterval(this.timer);
          this.timer = null;
        }
    },
    
  }
});